package middlewares

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"
	jaegercfg "github.com/uber/jaeger-client-go/config"
	jaegerlog "github.com/uber/jaeger-client-go/log"

	"routeApi/global"
)

func Trace() gin.HandlerFunc {
	return func(c *gin.Context) {
		// Sample configuration for testing. Use constant sampling to sample every trace
		// and enable LogSpan to log every span via configured Logger.
		cfg := jaegercfg.Configuration{
			// 全部采样
			Sampler: &jaegercfg.SamplerConfig{
				Type:  jaeger.SamplerTypeConst,
				Param: 1,
			},
			// 发送到jaeger 设置
			Reporter: &jaegercfg.ReporterConfig{
				// 打印上传Spans信息的日志
				LogSpans: true, //输出格式：traceid:spanid:父spanid
				// jaeger Agent地址
				LocalAgentHostPort: fmt.Sprintf("%s:%d", global.ServerConfig.JaegerInfo.Host, global.ServerConfig.JaegerInfo.Port),
			},
			ServiceName: global.ServerConfig.JaegerInfo.ServiceName,
		}

		// Initialize tracer with a logger and a metrics factory
		// 每次web请求一个tracer
		tracer, closer, err := cfg.NewTracer(jaegercfg.Logger(jaegerlog.StdLogger))
		if err != nil {
			panic(err)
			//log.Printf("Could not initialize jaeger tracer: %s", err.Error())
			//c.Status(http.StatusInternalServerError)
			//c.Abort()
			//return
		}
		opentracing.SetGlobalTracer(tracer)
		defer closer.Close()

		startSpan := tracer.StartSpan(c.Request.RequestURI)
		defer startSpan.Finish()

		c.Set("tracer", tracer)
		c.Set("parentSpan", startSpan)

		c.Next()

	}
}
